# 接口
from urllib import request, parse
from config import config
import json
import re


class DnsPodApi:
    def __init__(self, base_url):
        self.headers = {"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", 'Connection': 'close'}
        self.base_url = base_url
        self.response = None
    
    class Respone:
        def __init__(self, response_obj):
            self.__response_obj = response_obj
            self.response_data = self.response_data()
        
        def response_data(self):
            response_data = self.__response_obj.read().decode('utf-8')
            # print(response_data)
            self.response_data = json.loads(response_data)
            return self.response_data
        
        @property
        def response_status_code(self):
            response_status_code = self.response_data['status']['code']
            return response_status_code
        
        @property
        def response_record_id(self):
            response_record_id = self.response_data["record"]["id"]
            return response_record_id
        
        @property
        def response_record_name(self):
            response_record_name = self.response_data["record"]["name"]
            return response_record_name
        
        @property
        def response_latest_record_value_in_list(self):
            latest_record_value_in_list = self.response_data["records"][0]["value"]
            return latest_record_value_in_list
        
        @property
        def response_latest_record_id_in_list(self):
            latest_record_id_in_list = self.response_data["records"][0]["id"]
            return latest_record_id_in_list
        
        @property
        def status(self):
            return self.__response_obj.status
        
        @property
        def rsp_header(self):
            return self.__response_obj.getheaders()
    
    def request_api(self, url, data, headers, method='POST'):
        data = bytes(parse.urlencode(data), encoding='utf8')
        req = request.Request(url=url, data=data, headers=headers, method=method)
        response_obj = request.urlopen(req)
        return self.Respone(response_obj)
    
    def update_records(self, record_id, new_value, sub_domain=config["sub_domain"]):
        """"
        @record_id 记录id
        @new_value 新值,一般指外网IP
        修改dnspod解析记录
        
        """
        uri = "/Record.Modify"
        data = {
            "login_token": config["login_token"],
            "format": "json",
            "domain": config["domain"],
            "record_id": record_id,
            "sub_domain": sub_domain,
            "value": new_value,
            "record_type": config["record_type"],
            "record_line_id": config["record_line_id"],
            "line": config["line"],
            "status": "enable",
        }
        return self.request_api(self.base_url + uri, data, self.headers)
    
    def get_records_list(self, sub_domain=config["sub_domain"]):
        """"
        查询dnspod解析记录列表
        """
        uri = "/Record.List"
        data = {
            "login_token": config["login_token"],
            "format": "json",
            "domain": config["domain"],
            "sub_domain": sub_domain,
            "record_type": config["record_type"],
            "offset": 0,
            "length": 20
        }
        return self.request_api(self.base_url + uri, data, self.headers)
    
    def create_records(self, value, sub_domain=config["sub_domain"], record_type="A", record_line_id="0"):
        """"
        增加dnspod         解析记录
        sub_domain,        域名前缀
        record_type,       记录类型
        record_line_id,    默认0
        value              解析目的地
        """
        uri = "/Record.Create"
        data = {"login_token": config["login_token"],
                "format": "json",
                "domain": config["domain"],
                "sub_domain": sub_domain,
                "record_type": record_type,
                "record_line_id": record_line_id,
                "value": value}
        return self.request_api(self.base_url + uri, data, self.headers)
    
    def delete_records(self, record_id):
        """"
        增加dnspod         解析记录
        sub_domain,        域名前缀
        record_type,       记录类型
        record_line_id,    默认0
        value              解析目的地
        """
        uri = "/Record.Remove"
        data = {
            "login_token": config["login_token"],
            "format": "json",
            "domain": config["domain"],
            "record_id": record_id
        }
        return self.request_api(self.base_url + uri, data, self.headers)


def get_internet_ip():
    """获取外网IP地址"""
    url = "http://www.net.cn/static/customercare/yourip.asp"
    req = request.Request(url=url, headers={"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64)"})
    response = request.urlopen(req)
    response_data = response.read().decode("gb2312")
    obj = re.findall(r"<h2>(.*?)</h2>", str(response_data))
    internet_ip = obj[0]
    # print("当前的外网IP: %s" % internet_ip)
    return internet_ip
